package org.infosec.lc.exercises.ObjectNetworkTransmission.code.objectStream;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import org.infosec.lc.exercises.ObjectNetworkTransmission.modle.Person;

/**
	文件名：ObjectStreamUDPReceive.java
	作  者：林超
	时  间：2011-7-20下午02:16:28

	功能描述：接收网络中传输的ObjectInputStream,并还原为Person
	
	pom.xml	:
			
 */
public class ObjectStreamUDPReceive implements Runnable{
	
	private DatagramSocket o_dgSock;
	private DatagramPacket o_dgPack;
	
	{
		try {
			o_dgSock = new DatagramSocket(5000);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	
	public void run() {
		while(true){
			check();
			byte[] buf = new byte[1024];
			o_dgPack = new DatagramPacket(buf,0,1024);
			
			try {
				o_dgSock.receive(o_dgPack);
				
				byte[] data = o_dgPack.getData();
				
				ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
				
				try {
					Person person = (Person) ois.readObject();
					
					System.out.println(person.getName());
					System.out.println(person.getCardId().getAddress());
					
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void check(){
		if(o_dgSock==null)
			throw new NullPointerException("ObjectStreamUDPReceive o_dgSock is null");
	}
	
	public static void main(String[] args) {
		ObjectStreamUDPReceive osUDP = new ObjectStreamUDPReceive();
		
		Thread t = new Thread(osUDP);
		t.start();
	}
}

